#include "emulator_manager.h"
#include <stdio.h>
#include <stdlib.h>
#include <mainwindow.h>

HANDLE hBootThreadWaitEvent;
static unsigned char * romBuffer;


m64p_error Init()
{
    //CoreShutdown();
    CoreStartup();
    LoadRom("testrom.v64");

    return M64ERR_SUCCESS;
}

DWORD WINAPI Run(LPVOID /*lpParam*/)
{
    if (hBootThreadWaitEvent == NULL)
        hBootThreadWaitEvent = CreateEvent(NULL, FALSE, FALSE, L"BootEvent");

    if (!CoreDoCommand(M64CMD_EXECUTE, 0, NULL) != M64ERR_SUCCESS)
    {
        printf("\nFailed to execute core\n");
    }

    if (!CoreDoCommand(M64CMD_ROM_CLOSE, 0, NULL) != M64ERR_SUCCESS)
    {
       printf("Failed to close the rom\n");
    }

    SetEvent(hBootThreadWaitEvent);

    return 0;
}

m64p_error LoadRom(const char* romFileWithPath)
{
    FILE* romFile;
    long fileSize;

    // Open the file
    romFile = fopen(romFileWithPath, "rb");

    // Get the filesize
    fseek(romFile, 0, SEEK_END);
    fileSize = ftell(romFile);
    fseek(romFile, 0, SEEK_SET);

	if (romBuffer != NULL)
		free(romBuffer);

    // Allocate our memory buffer for the rom
    romBuffer = (unsigned char *)malloc(fileSize);

    // Copy all bytes into the buffer
    fread(romBuffer, 1, fileSize, romFile);

    // Close the file
    fclose(romFile);

    // Pass the pointer to mupen
    return CoreDoCommand(M64CMD_ROM_OPEN, fileSize, romBuffer);
}
